package cbfg.popup.demo

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment

class MainActivity : AppCompatActivity() {
    companion object {
        private const val ARG_TITLE = "title"
    }

    private var currentMenuItemId = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (savedInstanceState == null) {
            showFragment(R.id.actionDialogFragment)
        }
    }

    private fun showFragment(menuItemId: Int) {
        if (menuItemId == currentMenuItemId) {
            return
        }
        val fragment: Fragment = when (menuItemId) {
            R.id.actionDialogFragment -> {
                title = "Demo-DialogFragment"
                findFragmentByTag(title.toString()) ?: DFDemoFragment()
            }
            R.id.actionPopupWindow -> {
                title = "Demo-PopupWindow"
                findFragmentByTag(title.toString()) ?: PopupWindowFragment()
            }
            else -> return
        }
        supportFragmentManager.beginTransaction()
            .replace(android.R.id.content, fragment, title.toString())
            .commit()
    }

    private fun findFragmentByTag(tag: String?): Fragment? {
        return supportFragmentManager.findFragmentByTag(tag)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putCharSequence(ARG_TITLE, title)
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        title = savedInstanceState.getCharSequence(ARG_TITLE)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        showFragment(item.itemId)
        return true
    }
}